import store from "@utils/store/cookie";
import { getUserInfo } from "@api/user";

const LOGIN_KEY = "login_status";

const state = {
  isShowBack: true,
  isShowSearch: false,
  isBackGroundColor:false,
  title: ' ',
  token: store.get(LOGIN_KEY) || null,
  backgroundColor: "#FFFFFF",
  userInfo: null
};

const mutations = {
  SHOW_BACK(state) {
    state.isShowBack = true;
  },
  HIDE_BACK(state) {
    state.isShowBack = false;
  },
  SHOW_SEARCH(state) {
    state.isShowSearch = true;
  },
  HIDE_SEARCH(state) {
    state.isShowSearch = false;
  },
  SHOW_BACKGROUNDCOLOR(state) {
    state.isBackGroundColor = true;
  },
  HIDE_BACKGROUNDCOLOR(state) {
    state.isBackGroundColor = false;
  },
  SET_TITLE(state,title) {
    state.title = title
  },
  LOGIN(state, token, expires_time) {
    state.token = token;
    store.set(LOGIN_KEY, token, expires_time);
  },
  LOGOUT(state) {
    state.token = undefined;
    store.remove(LOGIN_KEY);
  },
  BACKGROUND_COLOR(state, color) {
    state.color = color;
    document.body.style.backgroundColor = color;
  },
  UPDATE_USERINFO(state, userInfo) {
    state.userInfo = userInfo;
  }
};

const actions = {
  USERINFO({ state, commit }, force) {
    if (state.userInfo !== null && !force)
      return Promise.resolve(state.userInfo);
    else
      return new Promise((resolve,reject) => {
        getUserInfo(force).then(res => {
          if (res.code){
            commit("UPDATE_USERINFO", res.data);
            resolve(res.data);
          }else {
            reject(res.msg)
          }
        });
      }).catch(() => {
        console.log("获取信息失败!");
      });
  }
};

export default {
  state,
  mutations,
  actions
};
